package com.apes.scm.masterdata.product.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Classify;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.StarProduct;
import com.apes.scm.masterdata.product.repository.ClassifyRepository;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.product.repository.StarProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: apes-server
 * @description:
 * @author: czs
 * @create: 2022-07-01 11:50
 **/
@Service("starProductService")
public class StarProductService extends DomainService {

    @Autowired
    private PartyRoleRepository partyRoleRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private StarProductRepository starProductRepository;
    @Autowired
    private ProductService productService;
    @Autowired
    private ClassifyRepository classifyRepository;

    public StarProduct createStarProduct(SimpleRequest request){
        JSONObject jo = request.getJO();
        String pid = jo.getString("U_ID");
        if (pid==null)pid=((PartyRole)request.getPerson()).getId();
        if (pid==null)throw new RuntimeException("找不到用户id");
        String productid = jo.getString("product");
        StarProduct starProduct = createOrChangeValidStarProduct(pid,productid);
        return starProductRepository.saveAndFlush(starProduct);
    }

    /**
     * 传入人员编码和商品编码,创建或者变更有效常用商品
     * @param pid
     * @param productid
     * @return
     */
    public StarProduct createOrChangeValidStarProduct(String pid, String productid){
        PartyRole starPerson = partyRoleRepository.findOne(pid);
        Product product = productRepository.findOne(productid);
        StarProduct starProduct = starProductRepository.findByProductAndStarPerson(product, starPerson);
        if (starProduct!=null){
            starProduct.setValid(!starProduct.isValid());
            return starProduct;
        }
        starProduct = new StarProduct();
        starProduct.setStarPerson(starPerson);
        starProduct.setProduct(product);
        return starProduct;
    }

    /**
     * 功能：查询常用工时
     *
     * @param request
     */
    public Page<Product> findStarProduct(SimpleRequest request) {
        List<Map> condition = request.  get("condition");
        PartyRole person = request.getPerson();
        condition.forEach(obj ->{
            Map map = new HashMap(obj);
            if("product.name".equals(map.get("field"))){
                obj.put("value", productService.regexSplit((String)map.get("value")));
            }
            if("starPerson.id".equals(map.get("field"))){
                obj.put("value", person.getId());
            }
        });
        Page<StarProduct> starProducts = starProductRepository.findAll(JpaDsl.toCriteria(condition), PageRequest.of(request.get("page"), request.get("size"), new Sort(Sort.Direction.DESC, "useNumber")));

        List<Product> productList = starProducts.getContent().stream().map(StarProduct::getProduct).collect(Collectors.toList());
        productList.forEach(product -> product.setStar(1));
        Page<Product> products = new PageImpl<Product>(productList,starProducts.getPageable(),starProducts.getTotalElements());

        return products;
    }


    public void createStarProductTest(SimpleRequest request){
        for (int i = 0; i < 1000; i++) {
            invoke("fn.service.createStarProduct", MapUtil.mapper("U_ID","0013785","product","000000"+(2499+i)));
        }
    }

    /**
     * 返回常用商品内分类树形数据
     * @param request
     * @return
     */
    public List<Map> findTreeNode(SimpleRequest request){
        PartyRole person = request.getPerson();
        //特例:洗车/美容/保养
        List ids = new ArrayList();
        ids.add("S0101");
        ids.add("S0102");
        ids.add("S0103");

        List<Product> products = starProductRepository.findAllProductByStarPerson(person.getId());
        List<Classify> classifyList = products.stream().map(Product::getClassify).collect(Collectors.toList());
        List<Classify> allParents = new ArrayList<>();
        //获取每个商品的所有父分类
        for (Classify classify : classifyList) {
            allParents.add(classify);
            Classify parentsClassify = classify.getParents();
            while (parentsClassify!=null){
                allParents.add(parentsClassify);
                parentsClassify=parentsClassify.getParents();
            }
        }
        allParents = allParents.stream().distinct().sorted(Comparator.comparing(Classify::getId)).collect(Collectors.toList());
        //子节点不再重复出现特例:洗车/美容/保养
        Map<String, List<Map>> parentsMap = allParents.stream().filter(classify -> !ids.contains(classify.getId())).map(classify -> {
            Map map = new HashMap();
            map.put("title", classify.getName());
            map.put("key", classify.getId());
            map.put("valid", classify.isValid());
            map.put("lastStage", classify.isLastStage());
            map.put("parents", classify.getParents() == null ? null : classify.getParents().getId());
            return map;
        }).collect(Collectors.groupingBy(m -> {
            if (m.get("parents") == null) {
                return "parent";
            }
            return m.get("parents").toString();
        }));
        //筛选顶级分类
        allParents = allParents.stream().filter(classify -> classify.getLevels() == 1).collect(Collectors.toList());
        List<Map> collect = allParents.stream().map(classify -> {
            Map map = new HashMap();
            map.put("title", classify.getName());
            map.put("key", classify.getId());
            map.put("valid", classify.isValid());
            if (parentsMap.get(classify.getId()) != null) {
                map.put("children", children(classify.getId(), parentsMap));
            }
            return map;
        }).collect(Collectors.toList());
        //顶级分类额外增加洗车/美容/保养
        ArrayList rows=new ArrayList();
        rows.add(MapUtil.mapper("field","id","operator","IN","value",ids));
        classifyList = classifyRepository.findAll(JpaDsl.toCriteria(rows));

        collect.addAll(classifyList.stream().map(classify -> {
            Map map = new HashMap();
            map.put("title", classify.getName());
            map.put("key", classify.getId());
            map.put("valid", classify.isValid());
            map.put("isLeaf",!classify.isLastStage());
            return map;
        }).collect(Collectors.toList()));
        return collect;

    }

    /**
     * 递归将值按前端格式返回
     *
     * @param parents
     * @param parentsMap
     * @return
     */
    public List<Map> children(String parents, Map<String, List<Map>> parentsMap) {
        List<Map> maps = new ArrayList<>();
        parentsMap.get(parents).forEach(map -> {
            Map result = new HashMap();
            result.put("title", map.get("title"));
            result.put("key", map.get("key"));
            result.put("valid", map.get("valid"));
            if (parentsMap.containsKey(map.get("key") )){
                result.put("children", children(map.get("key").toString(), parentsMap));
            }
            result.put("isLeaf", map.get("lastStage"));
            maps.add(result);
        });
        return maps;
    }
}
